package com.woodws.samples;

import com.woodws.mybatis.jpa.Definition;
import com.woodws.mybatis.jpa.builder.AbstractBuilder;
import com.woodws.mybatis.jpa.builder.DefaultResultMap;
import com.woodws.mybatis.jpa.builder.SqlFractional;
import com.woodws.mybatis.jpa.entity.ByProperty;
import com.woodws.mybatis.jpa.entity.Entity;
import com.woodws.mybatis.jpa.util.StrUtil;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.mapping.SqlCommandType;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by maoxiaodong on 2016/11/16.
 */
public class Function extends AbstractBuilder<Function>{
    private String funcName;

    public Function() {
        this.sqlCommandType = SqlCommandType.SELECT;
    }

    @Override
    protected String toSql() {
        return Definition.getNoTableSelect(dialect,funcName);
    }

    @Override
    protected SqlFractional parseMethodName() {
        SqlFractional sqlFractional = super.parseMethodName();
        Set<String> names = sqlFractional.getProperty();
        for(String name:names){
            funcName = StrUtil.camelToUnderline(name)+"()";
        }
        return sqlFractional;
    }

    @Override
    public void finish() {
        List<ResultMap> resultMaps;

        MappedStatement.Builder builder = new MappedStatement
                .Builder(configuration, id, getSqlSource(), sqlCommandType);
        String resultMapId = builder.id() + "-Inline";
        resultMaps = new ArrayList<ResultMap>();
        ResultMap.Builder resultMapBuilder = new ResultMap.Builder(
                configuration,
                resultMapId,
                returnType.getOwnerType(),
                new ArrayList<ResultMapping>());
        resultMaps.add(resultMapBuilder.build());
        builder.resultMaps(resultMaps);
        configuration.addMappedStatement(builder.build());
    }
}